package com.yang.booking.task;

import com.alibaba.fastjson.JSONArray;
import com.yang.booking.dao.StudentMapper;
import com.yang.booking.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class TaskService implements ApplicationRunner {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public void run(ApplicationArguments args) {

        try {
            ListOperations<String, String> listOperations = redisTemplate.opsForList();

            while (true) {
                handle(listOperations);
            }
        }catch (Exception e){
            System.out.println("e：" + e);
        }
    }

    @Transactional
    public void handle(ListOperations<String, String> listOperations) {
        String sr = listOperations.rightPop("list", 10, TimeUnit.SECONDS);
        if (sr != null) {
            System.out.println("s：" + sr);

            List<Student> ss = JSONArray.parseArray(sr, Student.class);
            for (Student s : ss
            ) {
                studentMapper.insert(s);
            }

            studentMapper.deleteById("03");

            Student us = new Student();
            us.setsId("09");
            us.setsName("周元");
            us.setsBirth("200-09-01");
            us.setsSex("男");
            studentMapper.updateById(us);
        }
    }
}
